package com.zhsj.OkeHomeConsumption.ui.fragment.integral.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.hjq.bar.TitleBar;
import com.orhanobut.hawk.Hawk;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.other.QRCodeUtil;
import com.zhsj.OkeHomeConsumption.ui.activity.WebActivity;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.WindowUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 面对面邀请
 */
public class InviteFaceActivity extends MyActivity {
    @BindView(R.id.title_back)
    TitleBar titleBack;
    @BindView(R.id.weixin_linear)
    LinearLayout weixinLinear;
    @BindView(R.id.weixin_circle_linear)
    LinearLayout weixinCircleLinear;
    @BindView(R.id.save_image_linear)
    LinearLayout saveImageLinear;
    @BindView(R.id.code_image)
    ImageView codeImage;

    Bitmap bitmap;
    @BindView(R.id.image_code_linear)
    LinearLayout imageCodeLinear;

    //用户信息
    private FormalUserInfo formalUserInfo;
    //用户id
    private String userId;
    //保存图片使用的布局
    View view;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_invite_face;
    }

    @Override
    protected int getTitleId() {
        return R.id.title_back;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        formalUserInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        userId = String.valueOf(formalUserInfo.getId());
        int width = WindowUtils.getWindowWidthPixels(getApplicationContext()) / 2 - 50;
        ViewGroup.LayoutParams layoutParams = codeImage.getLayoutParams();
        layoutParams.width = width;
        layoutParams.height = width;
        codeImage.setLayoutParams(layoutParams);
        LogUtils.e("屏幕宽度", width + "");
        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.androidicon1);
        bitmap = QRCodeUtil.createQRImage(OkeHomeConsumptionApi.ELVDOU_BASEURL_H5 + "app/h5/platform/12.html?userid=" + userId + "&invite=" + userId + "&type=1&rtype=1", width, width, logo, "");
        Glide.with(getActivity()).load(bitmap).into(codeImage);

        view = getLayoutInflater().inflate(R.layout.image_code, null);
        ImageView code_image = view.findViewById(R.id.code_image);
        Glide.with(getActivity()).load(bitmap).into(code_image);
    }

    /**
     * 有标题点击事件
     * 规则
     *
     * @param v
     */
    @Override
    public void onRightClick(View v) {
        super.onRightClick(v);
        Intent intent = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5 + "app/h5/platform/32.html");
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.weixin_linear, R.id.weixin_circle_linear, R.id.save_image_linear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.weixin_linear:
                UMImage image = new UMImage(getActivity(), bitmap);//bitmap文件
                new ShareAction(getActivity())
                        .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                        .withMedia(image)
                        .setCallback(umShareListener)//回调监听器
                        .share();
                break;
            case R.id.weixin_circle_linear:
                UMImage image1 = new UMImage(InviteFaceActivity.this, bitmap);//bitmap文件
                image1.compressStyle = UMImage.CompressStyle.SCALE;
                new ShareAction(InviteFaceActivity.this)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                        .withMedia(image1)
                        .setCallback(umShareListener)//回调监听器
                        .share();
                break;
            case R.id.save_image_linear:
                getBitmap();
                break;
        }
    }

    /**
     * @Fields umShareListener : TODO 监听分享后的状态
     */
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
//            toast("分享活动成功啦");

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {

            toast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

            toast("分享取消了");
        }
    };

    private void getBitmap() {

        int me = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(me, me);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmapCode = view.getDrawingCache();
        saveCroppedImage(bitmapCode);
    }


    /**
     * 保存图片到本地
     */
    private void saveCroppedImage(Bitmap bitmap) {
        File file = new File("/sdcard/聚联惠");
        if (!file.exists())
            file.mkdir();
        String time = getPhoneTimeStrMiao();
        file = new File("/sdcard/" + time + ".jpg".trim());
        String fileName = file.getName();
        String mName = fileName.substring(0, fileName.lastIndexOf("."));
        String sName = fileName.substring(fileName.lastIndexOf("."));

        // /sdcard/myFolder/temp_cropped.jpg
        String newFilePath = "/sdcard/聚联惠" + "/" + mName + "_julianhui" + sName;
        file = new File(newFilePath);
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            toast("图片已保存成功");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 通知图库更新
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            MediaScannerConnection.scanFile(this, new String[]{file.getAbsolutePath()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            mediaScanIntent.setData(uri);
                            sendBroadcast(mediaScanIntent);
                        }
                    });
        } else {
            String relationDir = file.getParent();
            File file1 = new File(relationDir);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
        }
    }

    private String getPhoneTimeStrMiao() {
        //获取当前时间戳
        long timeStamp = System.currentTimeMillis();
        String timeSre = timeStamp + "";
        String resultStr = timeSre.substring(0, 10);
        return resultStr;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap != null) {
            bitmap.recycle();
        }
    }
}
